<template>
  <div class="container">
    <div>
      <div class="alert alert-dark alert-dismissible" v-show="show.inputWarning">
        <strong>出错咯：</strong>请检查您输入的内容！
        <button type="button" class="close" @click="show.inputWarning==false">&times;</button>
      </div>
      <div class="alert alert-dark alert-dismissible" v-show="show.verifyWarning">
        Failed to verify
        <button
          type="button"
          class="close"
          @click="show.inputWarning==false"
        >&times;</button>
      </div>
    </div>
    <div class="form-group">
      <input type="text" class="form-control" placeholder="Token" v-model="input" />
      <button type="button" class="btn btn-dark" @click="verify">Verify</button>
    </div>
  </div>
</template>

<script>
export default {
  name: "AdminVerifyView",
  data() {
    return {
      input: "",
      show: {
        inputWarning: false,
        verifyWarning: false
      }
    };
  },
  computed: {
    devMode() {
      return this.$store.state.devMode;
    },
    isValid() {
      return this.$store.state.isAdmin;
    },
    tokenStr() {
      return this.$store.state.tokenStr;
    }
  },
  methods: {
    verify() {
      if (this.input.length == 0) {
        //input warning
        this.show.inputWarning = true;
      } else {
        this.axios
          .post("backend.php", {
            action: "verify",
            payload: {
              token: this.input
            }
          })
          .then(response => {
            if (this.devMode) {
              window.console.log(response);
            }
            if (response.data.valid) {
              this.$store.commit("verifyAdmin", this.input);
              this.$router.push("admin");
            } else {
              //invalid warning
              this.show.verifyWarning = true;
            }
          })
          .catch(error => {
            if (this.devMode) {
              window.console.log(error);
            }
          });
      }
    }
  },
  mounted() {
    if (this.isValid) {
      this.$router.push("background");
    }
  }
};
</script>

<style scoped>
.alert {
  text-align: left;
}
</style>